package homework.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 根据随机数，选取使用的服务器
 */
public class HeaderHttpRequestFilter implements HttpRequestFilter {

    private ArrayList<String> servers;

    public HeaderHttpRequestFilter(ArrayList<String> servers) {
        this.servers = servers;
    }

    @Override
    public void filter(FullHttpRequest fullRequest, ArrayList<String> servers, ChannelHandlerContext ctx) {
        fullRequest.headers().setInt("server", this.getIdx(servers));
    }

    public int getIdx(List<String> servers) {
        int size = servers.size();
        Random random = new Random(System.currentTimeMillis());
        return random.nextInt(size);
    }
}
